import { useRequest } from 'ahooks'
import type { Options } from 'ahooks/lib/useRequest/src/types'
import axios from 'axios'

import './__mock__'

/** 时区 */
export interface ITimeZone {
  // UTC偏移量
  utcOffset: string
  // 主要城市、地区和国家描述
  regions: string
}

export interface TTimeZoneRes {
  list: ITimeZone[]
  /** 以 utcOffset 为键的映射 */
  offsetMap: Record<string, ITimeZone | undefined>
  /** 以 regions 为键的映射 */
  regionsMap: Record<string, ITimeZone | undefined>
}

/** SWR 时区 获取时区列表 */
export const useTimeZoneList = (opts?: Options<TTimeZoneRes, []>) => {
  return useRequest<TTimeZoneRes, []>(
    async () => {
      const res = await axios.get(`/tmsapi/waybill_record_v2/zone_list`)
      const list: ITimeZone[] = res.$data || []
      const offsetMap = list.reduce<Record<string, ITimeZone | undefined>>((o, i) => ({ ...o, [i.utcOffset]: i }), {})
      const regionsMap = list.reduce<Record<string, ITimeZone | undefined>>((o, i) => ({ ...o, [i.regions]: i }), {})
      return { list, offsetMap, regionsMap }
    },
    {
      cacheTime: -1, // 永不过期
      staleTime: -1, // 永远新鲜
      ...opts,
      cacheKey: 'SWRApi_useTimeZoneList',
    },
  )
}
